package cn.kongwg.java;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author kongwg
 * @create 2021-01-29 10:25
 */
@WebServlet("/sessionServlet")
public class SessionServlet extends BaseServlet {

    protected void getSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();

        String id = session.getId();

        boolean aNew = session.isNew();

        resp.getWriter().write("获得一个Session <br/>");
        resp.getWriter().write("Session的id： " + id + "<br/>");
        resp.getWriter().write("是不是新创建的Session <br/>" + aNew);
    }

    protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setAttribute("key1", "value1");
        resp.getWriter().write("已向key1中存储了数据");
    }

    protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String key1 = (String) req.getSession().getAttribute("key1");
        resp.getWriter().write(key1);
    }

    protected void setLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int maxInactiveInterval = req.getSession().getMaxInactiveInterval();
        resp.getWriter().write("磨人的时间："+maxInactiveInterval);
    }

    protected void setLife3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().setMaxInactiveInterval(3);
        resp.getWriter().write("设置3秒钟后session过期");
    }

    protected void setLife0(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.getSession().invalidate();

      resp.getWriter().write("设置立刻过期");
    }
}
